package top.kaoshanji.q1ch05a.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import top.kaoshanji.q1ch05a.dao.SpitterRepository;
import top.kaoshanji.q1ch05a.model.Spitter;

import javax.validation.Valid;

/**
 * @author kaoshanji
 * ^_^
 * create time 2025/4/24 15:56
 */
@Controller
@RequestMapping("/spitter")
public class SpitterController {

    private SpitterRepository spitterRepository;

    @Autowired
    public SpitterController(SpitterRepository spitterRepository) {
        this.spitterRepository = spitterRepository;
    }

    /**
     * 代码清单-q1ch05a-158页a：展现一个表单，允许用户注册该应用
     * @return 视图逻辑名
     */
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String showRegistrationForm() {
        return "showRegistrationFormPage";
    }

    /**
     * 代码清单-q1ch05a-161页a：处理所提交的表单并注册新用户
     * 代码清单-q1ch05a-165页a：确保所提交的数据是合法的
     * @param spitter Spitter
     * @return 视图逻辑名
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String processRegistration(@Valid Spitter spitter, Errors errors) {
        System.out.println("...............");

        if (errors.hasErrors()) {
            return "showRegistrationFormPage";
        }

        spitterRepository.save(spitter);

        return "redirect:/spitter/spitterDetail/" + spitter.getUsername();
    }

    /**
     * 代码清单-q1ch05a-162页a：显式用户详情
     * @param username
     * @param model
     * @return
     */
    @RequestMapping(value = "/spitterDetail/{username}")
    public String spitterDetail(@PathVariable("username") String username, Model model) {
        Spitter spitter = spitterRepository.findByUsername(username);
        model.addAttribute("spitter", spitter);

        return "spitterDetailPage";
    }


}
